package 二叉树;

import com.alibaba.fastjson.JSON;

import java.util.*;

public class NC136输出二叉树的右视图 {

    /**
     * 请根据二叉树的前序遍历，中序遍历恢复二叉树，并打印出二叉树的右视图
     *
     * 示例1
     * 输入
     * 复制
     * [1,2,4,5,3],[4,2,5,1,3]
     * 返回值
     * 复制
     * [1,3,5]
     * 备注:
     * 二叉树每个节点的值在区间[1,10000]内，且保证每个节点的值互不相同。
     */

    private Map<Integer,Integer> map=new HashMap<>();
    private int[] xianxu;
    private int[] zhongxu;

    public int[] solve (int[] xianxu, int[] zhongxu) {
        this.xianxu=xianxu;
        this.zhongxu=zhongxu;
        for (int i = 0; i < zhongxu.length; i++) {
            map.put(zhongxu[i],i);
        }
        TreeNode root = createTreeNode(0, xianxu.length - 1, 0, zhongxu.length - 1);

        //右视图
        List<Integer> list = rightView(root);
        int[] result=new int[list.size()];

        for (int i = 0; i < list.size(); i++) {
            result[i]=list.get(i);
        }

        return result;
    }

    private TreeNode createTreeNode(int xLeft,int xRight,int zLeft,int zRight){

        if(xLeft>xRight||zLeft>zRight){
            return null;
        }

        TreeNode root=new TreeNode(xianxu[xLeft]);

        int zIndex=map.get(xianxu[xLeft]);
        int leftSub=zIndex-zLeft;
        root.left=createTreeNode(xLeft+1,xLeft+leftSub,zLeft,zIndex-1);
        root.right=createTreeNode(xLeft+leftSub+1,xRight,zIndex+1,zRight);

        return root;
    }

    private List<Integer> rightView(TreeNode root){
        List<Integer> list=new ArrayList<>();
        dfs(root,1,list);
        return list;
    }

    private void dfs(TreeNode node,int deep,List<Integer> list){
        if(node==null){
            return;
        }
        if(deep>list.size()){
            list.add(node.val);
        }
        dfs(node.right,deep+1,list);
        dfs(node.left,deep+1,list);
    }

    public static void main(String[] args) {
        NC136输出二叉树的右视图 n=new NC136输出二叉树的右视图();
        int[] qianxu={3,9,20,15,7};
        int[] zhongxu={9,3,15,20,7};
        int[] result = n.solve(qianxu, zhongxu);
        System.out.println(JSON.toJSONString(result));
    }

}
